package xyz.migle.base.task;

import java.sql.Connection;
import java.sql.SQLException;
import xyz.migle.base.Task;
import xyz.migle.util.DBUtil;

/**
 * 执行通用的SQL语句 //for mysql jdbc.driverClassName =com.mysql.jdbc.Driver jdbc.url =
 * jdbc:mysql://{ip}:{port}/{dbName} jdbc.user = {} jdbc.pass = {}
 *
 * //for db2 jdbc.driverClassName =com.ibm.db2.jcc.DB2Drive jdbc.url =
 * jdbc:db2://{ip}:{port}/{dbName} jdbc.user = {} jdbc.pass = {}
 */
public class SQLTask implements Task<Boolean> {

  private String taskName;
  private String describe;
  private String type;
  private String url;
  private String user;
  private String pwd;
  private String sql;
  private String driverClassName;

//hive:org.apache.hive.jdbc.HiveDriver
//mysql:
//db2:
  
  @Override
  public Boolean exec() {
    System.out.println("开始执行");
    try {
      System.err.println("driverClassName:"+driverClassName);
      Class.forName(driverClassName);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    try (Connection connection = DBUtil.getConnection(this.url, this.user, this.pwd)) {
      connection.createStatement().execute(this.sql);
      System.out.println("执行成功:"+this.sql);
    } catch (SQLException e) {
      e.printStackTrace();
      System.out.println("执行出错:" + this.sql);
      return false;
    }
    return true;
  }

  public String getType() {
    return type;
  }

  public void setType(String type) {
    this.type = type;
  }

  public String getUrl() {
    return url;
  }

  public void setUrl(String url) {
    this.url = url;
  }

  public String getUser() {
    return user;
  }

  public void setUser(String user) {
    this.user = user;
  }

  public String getPwd() {
    return pwd;
  }

  public void setPwd(String pwd) {
    this.pwd = pwd;
  }

  public String getSql() {
    return sql;
  }

  public void setSql(String sql) {
    this.sql = sql;
  }

  public String getTaskName() {
    return taskName;
  }

  public void setTaskName(String taskName) {
    this.taskName = taskName;
  }

  public String getDescribe() {
    return describe;
  }

  public void setDescribe(String describe) {
    this.describe = describe;
  }

  public String getDriverClassName() {
    return driverClassName;
  }

  public void setDriverClassName(String driverClassName) {
    this.driverClassName = driverClassName;
  }

  @Override
  public String toString() {
    final StringBuilder sb = new StringBuilder("SQLTask{");
    sb.append("taskName='").append(taskName).append('\'');
    sb.append(", describe='").append(describe).append('\'');
    sb.append(", type='").append(type).append('\'');
    sb.append(", url='").append(url).append('\'');
    sb.append(", user='").append(user).append('\'');
    sb.append(", pwd='").append(pwd).append('\'');
    sb.append(", sql='").append(sql).append('\'');
    sb.append(", driverClassName='").append(driverClassName).append('\'');
    sb.append('}');
    return sb.toString();
  }
}
